//
//  FSBaseVC.m
//  MWB2C
//
//  Created by CoolCamel on 2017/11/20.
//  Copyright © 2017年 www.meiweigx.com. All rights reserved.
//

#import "FSBaseVC.h"
NSString *const kBiz_HideKeyboard = @"hide_keyboard";

//@interface UINavigationCustomTransition :   NSObject<UIViewControllerAnimatedTransitioning>
//@end
//
//@protocol UIGestureRecognizerDelegate;

//@implementation UINavigationCustomTransition

//-(NSTimeInterval) transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
//    return .3;
//}

//-(void) animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
//    UIViewController* toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
//    UIViewController* fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
//    [[transitionContext containerView] insertSubview:toViewController.view belowSubview:fromViewController.view];
//    //toViewController.view.alpha = .5;
//    //toViewController.view.transform = CGAffineTransformMakeScale(.9, .9);
//    [UIView transitionWithView:[transitionContext containerView] duration:[self transitionDuration:transitionContext]
//                       options:UIViewAnimationOptionCurveLinear animations:^{
//                           fromViewController.view.transform = CGAffineTransformMakeTranslation([UIScreen mainScreen].bounds.size.width, 0);
//                           //fromViewController.view.alpha = .5;
//                           //toViewController.view.alpha = 1;
//                           //toViewController.view.transform = CGAffineTransformIdentity;
//                       } completion:^(BOOL finished) {
//                           [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
//                       }];
//}
//@end

@interface FSBaseVC ()
<UINavigationControllerDelegate,
UIGestureRecognizerDelegate
>

@property (nonatomic, strong) UIPanGestureRecognizer *panGesture;   //滑动手势，默认支持手势滑动，若要禁用，则enabled为No;
//@property (nonatomic, strong) UINavigationCustomTransition *customTransition;
@property (nonatomic, strong) UIPercentDrivenInteractiveTransition *interactivePopTransition;
@property (nonatomic,assign) BOOL ajustedIphoneX;
@property (nonatomic, strong) UIView *backgroundTipView;
@property (nonatomic, copy) NSString *navTitle;///< <#code annotation#>
@end

@implementation FSBaseVC

//-(instancetype) init{
//    if (self = [super init]) {
//        _isEnableCustomTransition = NO;    //默认支持手势滑动;
//    }
//    return self;
//}

- (instancetype) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        _isEnableCustomTransition = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBackButton];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        self.m_yOffset = [[[UIApplication sharedApplication] delegate] window].frame.origin.y + 10 + 40 + 20;
        // ios系统大于7，为避免出现输入框字符下沉，需添加以下配置
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
        [self setExtendedLayoutIncludesOpaqueBars:NO];
    }
    else {
        self.m_yOffset = [[[UIApplication sharedApplication] delegate] window].frame.origin.y + 10 + 40;
    }
    //创建手势滑动
    [self.navigationController.navigationBar.backItem setHidesBackButton:YES];
    
    KSLog(@"当前VC  ----------------------------------------------------------------------------------------------------------------------------------------------------   %@",self);
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.navigationController.childViewControllers.count > 1) {
        __weak typeof(self) weakSelf = self;
        self.navigationController.delegate = weakSelf;
    }else{
        self.navigationController.delegate = nil;
    }
    [self adjustiPhoneX];
    [self setNavigationBarBackgroundColorBlue];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.delegate = nil;
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    //    NSString * pageID = NSStringFromClass(self.class);
    //[MobClick beginLogPageView:pageID];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    //    NSString * pageID = NSStringFromClass(self.class);
    // [MobClick endLogPageView:pageID];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void) dealloc {
    
}

- (void)didReceiveMemoryWarning {
    
}

#pragma Public
-(void) setIsEnableCustomTransition:(BOOL)isEnableCustomTransition{
    _isEnableCustomTransition = isEnableCustomTransition;
    if ([self isViewLoaded]) {//已经创建View，如果未创建，则会走viewDidLoad这里，会再次进行设置
        _panGesture.enabled = _isEnableCustomTransition;
    }
}

- (void)showNavigationBarShadowImage{
    
    self.navigationController.navigationBar.shadowImage = nil;
    
}

- (void)hiddenNavigationBarShadowImage{
    self.navigationController.navigationBar.shadowImage =  [[UIImage alloc] init];;
}

- (void)setTitleViewWithView:(UIView *)view {
    self.navigationItem.titleView = view;
}

- (void)setTitleWithTitle:(NSString *)title {
    UILabel * lblTitle = (UILabel *)self.navigationItem.titleView;
    
    if(nil == lblTitle) {
        lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
        lblTitle.backgroundColor = [UIColor colorWithRed:26.0/255 green:26.0/255 blue:26.0/255 alpha:1.0];
        lblTitle.font = [UIFont systemFontOfSize:17];
        lblTitle.textColor = [UIColor colorWithRed:26.0/255 green:26.0/255 blue:26.0/255 alpha:1.0];
        lblTitle.textAlignment = NSTextAlignmentCenter;
        
        self.navigationItem.titleView = lblTitle;
    }
    
    lblTitle.text = title;
}

- (void)setTitleWithTitle:(NSString *)title Color:(UIColor *)color {
    UILabel * lblTitle = (UILabel *)self.navigationItem.titleView;
    
    if(nil == lblTitle) {
        lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
        lblTitle.font = [UIFont systemFontOfSize:17];
        lblTitle.textColor = color;
        lblTitle.textAlignment = NSTextAlignmentCenter;
        
        self.navigationItem.titleView = lblTitle;
    }
    
    lblTitle.text = title;
}

- (void)setLeftBarButtonItemsWithButtonItems:(NSArray<UIBarButtonItem *> *)buttonItems {
    [self.navigationItem setLeftBarButtonItems:buttonItems];
}

- (void)setRightBarButtonItemsWithButtonItems:(NSArray<UIBarButtonItem *> *)buttonItems {
    [self.navigationItem setRightBarButtonItems:buttonItems];
}

- (void)setLeftBarButtonItemWithImage:(UIImage *)image Action:(SEL)action {
    
    UIImage * originalImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem * leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:originalImage
                                                                           style:UIBarButtonItemStylePlain
                                                                          target:self
                                                                          action:action];
    
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
}

- (void)setRightBarButtonItemWithImage:(UIImage *)image Action:(SEL)action {
    
    UIImage * originalImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem * rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:originalImage
                                                                            style:UIBarButtonItemStylePlain
                                                                           target:self
                                                                           action:action];
    
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
}

- (void)setRightBarButtonItemWithTitle:(NSString *)title Attributes:(NSDictionary *)attributes Action:(SEL)action {
    
    UIBarButtonItem * rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:title
                                                                            style:UIBarButtonItemStylePlain
                                                                           target:self
                                                                           action:action];
    
    [rightBarButtonItem setTitleTextAttributes:attributes forState:UIControlStateNormal];
    [rightBarButtonItem setTitleTextAttributes:attributes forState:UIControlStateHighlighted];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
}

- (void)setRightBarButtonItemWithTitle:(NSString *)title Action:(SEL)action {
    [self setRightBarButtonItemWithTitle:title Attributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0xffffff),
                                                            NSFontAttributeName:[UIFont systemFontOfSize:15]
    } Action:action];
}

- (void)setLeftBarButtonItemWithTitle:(NSString *)title Attributes:(NSDictionary *)attributes Action:(SEL)action {
    
    UIBarButtonItem * leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:title
                                                                           style:UIBarButtonItemStylePlain
                                                                          target:self
                                                                          action:action];
    
    [leftBarButtonItem setTitleTextAttributes:attributes forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
}

- (void)setLeftImage:(UIImage *)image Title:(NSString *)title Action:(SEL)action{
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor clearColor]; //加上背景颜色，方便观察Button的大小
    [button addTarget:self action:action forControlEvents:UIControlEventTouchDown];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //设置图片
    //       UIImage *p_w_picpathForButton = [UIImage p_w_picpathNamed:@"oicon_01"];
    [button setImage:image forState:UIControlStateNormal];
    
    //设置文字
    NSString *buttonTitleStr = title;
    [button setTitle:buttonTitleStr forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    //       [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    CGSize buttonTitleLabelSize = [buttonTitleStr sizeWithAttributes:@{NSFontAttributeName:button.titleLabel.font}]; //文本尺寸
    CGSize buttonImageSize = image.size;   //图片尺寸
    button.frame = CGRectMake(0,0,
                              buttonImageSize.width + buttonTitleLabelSize.width,
                              buttonImageSize.height);
    button.titleLabel.textAlignment = NSTextAlignmentLeft;
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = barButtonItem;
}



- (void)setLeftImageMessage:(UIImage *)image Title:(NSString *)title Action:(SEL)action{
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
    backView.backgroundColor = [UIColor clearColor];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor clearColor]; //加上背景颜色，方便观察Button的大小
    [button addTarget:self action:action forControlEvents:UIControlEventTouchDown];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //设置图片
    [button setImage:image forState:UIControlStateNormal];
    
    //设置文字
    NSString *buttonTitleStr = @"";
    [button setTitle:buttonTitleStr forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    
    CGSize buttonImageSize = image.size;   //图片尺寸
    button.frame = CGRectMake(0,13,
                              80,
                              buttonImageSize.height);
    button.titleLabel.textAlignment = NSTextAlignmentLeft;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    UILabel *labMessage = [[UILabel alloc]initWithFrame:CGRectMake(10, 13, 8, 8)];
    labMessage.layer.cornerRadius = 4;
    labMessage.backgroundColor = [FSFormatTool colorWithHexString:@"#DB0C0C"];
    labMessage.textColor = [UIColor whiteColor];
    labMessage.layer.masksToBounds = YES;
    labMessage.textAlignment = NSTextAlignmentCenter;
    labMessage.font = [UIFont systemFontOfSize:6];
    labMessage.text = title;
    if (title.integerValue == 0) {
        labMessage.hidden = YES;
    }else{
        labMessage.hidden = NO;
    }
    
    [backView addSubview:button];
    [backView addSubview:labMessage];
    self.navigationItem.leftBarButtonItem  = [[UIBarButtonItem alloc]initWithCustomView:backView];
}


- (void)setBackButton {
    [self setLeftBarButtonItemWithImage:[UIImage imageNamed:@"返回"] Action:@selector(pop)];
}


- (void)setBackBaiButton {
    [self setLeftBarButtonItemWithImage:[UIImage imageNamed:@"首页返回"] Action:@selector(pop)];
}

- (void)hideBackButton {
    self.navigationItem.leftBarButtonItem = nil;
    
    self.navigationItem.hidesBackButton = YES;
}

- (void)pop{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)settranslucentNO{
    self.navigationController.navigationBar.translucent = NO;
    
}
- (void)settranslucentYES{
    self.navigationController.navigationBar.translucent = YES;
    
}

- (void)hideTitle {
    self.navigationItem.titleView = nil;
}

- (void)hideLeftBarButtonItem {
    self.navigationItem.leftBarButtonItem = nil;
}

- (void)hideRightBarButtonItem {
    
    self.navigationItem.rightBarButtonItem = nil;
}
- (void)pushAndHiddenBottomBarToVC:(UIViewController *)vc {
    if (self.navigationController) {
        if (self.navigationController.viewControllers.count == 1) {
            vc.hidesBottomBarWhenPushed = YES;
        }
        else {
            vc.hidesBottomBarWhenPushed = NO;
        }
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void) popViewController {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.navigationController) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    });
}

- (void) popViewRootViewController;{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.navigationController) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    });
}

//显示/隐藏导航栏
-(void)showNavigationBarHidden:(BOOL)hidden{
    [self.navigationController setNavigationBarHidden:hidden animated:YES];
}
#pragma Private
#pragma Private
- (void)adjustiPhoneX {
    if (self.ajustedIphoneX) return;
    if (@available(iOS 11.0, *)) {
        NSArray *c = self.view.constraints;
        for (NSLayoutConstraint *l in c) {
            if (l.secondItem == self.view && l.firstAttribute==NSLayoutAttributeTop) {
                if (fabs([UIScreen mainScreen].bounds.size.height - 812.0) < 1.0) {//iPhone X
                    if (![l.firstItem isKindOfClass:[UIScrollView class]] &&
                        self.navigationController.navigationBar.hidden
                        ) {
                        l.constant += 44;
                    }
                }
            }
        }
        self.ajustedIphoneX = YES;
    }
}


- (void)setNavigationBarBackgroundColorWithColor:(UIColor *)color {
    
    
    UIImage * navigationBKImage = [UIImage imageWithColor:color
                                                     size:CGSizeMake(iPhone_Width,
                                                                     iPhone_NavigationBar_Height)];
    [self.navigationController.navigationBar setBackgroundImage:navigationBKImage forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}
//白色背景
- (void)setNavigationBarBackgroundColorWhite:(NSString *)titleName{
    UIImage * navigationBKImage = [UIImage imageWithColor:[FSFormatTool colorWithHexString:@"#ffffff"]
                                                     size:CGSizeMake(iPhone_Width,
                                                                     iPhone_NavigationBar_Height)];
    [self.navigationController.navigationBar setBackgroundImage:navigationBKImage forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    [self setLeftBarButtonItemWithImage:[UIImage imageNamed:@"左箭头"] Action:@selector(pop)];
    [self setTitleWithTitle:titleName Color:[FSFormatTool colorWithHexString:@"#333333"]];
}
//白色背景
- (void)setNavigationBarBackgroundColor{
    
}

//蓝色背景
- (void)setNavigationBarBackgroundColorBlue{
    UIImage * navigationBKImage = [UIImage imageWithColor:COLOR_WINDOW_THEME
                                                     size:CGSizeMake(iPhone_Width,
                                                                     iPhone_NavigationBar_Height)];
    [self.navigationController.navigationBar setBackgroundImage:navigationBKImage forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    [self setLeftBarButtonItemWithImage:[UIImage imageNamed:@"返回"] Action:@selector(pop)];
}

- (void)handlePopRecognizer:(UIPanGestureRecognizer*)recognizer {
    UIView* view = self.view;
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint location = [recognizer locationInView:view];
        if (location.x <  CGRectGetMidX(view.bounds) && self.navigationController.viewControllers.count > 1) { // left half
            self.interactivePopTransition = [[UIPercentDrivenInteractiveTransition alloc] init];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else if (recognizer.state == UIGestureRecognizerStateChanged) {
        CGPoint translation = [recognizer translationInView:view];
        CGFloat d = translation.x / CGRectGetWidth(view.bounds);
        [self.interactivePopTransition updateInteractiveTransition:d];
    } else if (recognizer.state == UIGestureRecognizerStateEnded) {
        if ([recognizer velocityInView:view].x > 0) {
            [self.interactivePopTransition finishInteractiveTransition];
        } else {
            [self.interactivePopTransition cancelInteractiveTransition];
        }
        self.interactivePopTransition = nil;
    }
}

#pragma UINavigationControllerDelegate
//- (nullable id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
//                                   interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController{
//    return self.interactivePopTransition;
//
//}
//
//- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
//                                            animationControllerForOperation:(UINavigationControllerOperation)operation
//                                                         fromViewController:(UIViewController *)fromVC
//                                                           toViewController:(UIViewController *)toVC {
//    if (operation == UINavigationControllerOperationPop && fromVC == self) {
//        return self.customTransition;
//    }
//    return nil;
//}

//- (void)routerEventWithName:(NSString *)eventName dataInfo:(NSDictionary *)dataInfo {
//    [super routerEventWithName:eventName dataInfo:dataInfo];
//    if ([eventName isEqualToString:kBiz_HideKeyboard]) {
//        [self.view endEditing:YES];
//    }
//}


#pragma mark -- 无数据背景图
- (UIView *)backgroundTipView
{
    if (!_backgroundTipView) {
        _backgroundTipView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-100)];
        _backgroundTipView.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"暂无数据"]];
        imageView.frame = CGRectMake(0, 95, iPhone_Width, 150);
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_backgroundTipView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(imageView.frame) + 10, _backgroundTipView.frame.size.width, 20)];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"暂无数据";
        label.font = [UIFont systemFontOfSize:18];
        label.textColor = [FSFormatTool colorWithHexString:@"#888888"];
        [_backgroundTipView addSubview:label];
    }
    return _backgroundTipView;
}
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if (self.navigationController.viewControllers.count == 1) {
        return NO;
    }
    return YES;
}

@end
